import { DataSource } from 'typeorm';
import { Project } from '../../../entities/project.entity';
import { Workspace } from '../../../entities/workspace.entity';
import { User } from '../../../entities/user.entity';
import { ProjectStatus } from '../../../types/enums';

/**
 * 项目种子数据
 * 负责初始化示例项目
 */
export class ProjectSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行项目种子
   */
  async run(): Promise<void> {
    console.log('开始初始化项目数据...');

    const projectRepository = this.dataSource.getRepository(Project);
    const workspaceRepository = this.dataSource.getRepository(Workspace);
    const userRepository = this.dataSource.getRepository(User);

    // 查找管理员用户
    const adminUser = await userRepository.findOneBy({ username: 'admin' });

    if (!adminUser) {
      console.log('未找到管理员用户，跳过项目初始化');
      return;
    }

    // 查找所有工作区
    const workspaces = await workspaceRepository.find();

    if (workspaces.length === 0) {
      console.log('未找到工作区，跳过项目初始化');
      return;
    }

    // 为每个工作区创建示例项目
    for (const workspace of workspaces) {
      const projectsData = [
        {
          name: '产品开发项目',
          description: '开发新产品的项目，包括设计、开发和测试阶段',
          workspaceId: workspace.id,
          createdById: adminUser.id,
          status: ProjectStatus.ACTIVE,
          startDate: new Date(),
          endDate: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000), // 90天后
        },
        {
          name: '网站重构项目',
          description: '对现有网站进行重新设计和开发，提升用户体验',
          workspaceId: workspace.id,
          createdById: adminUser.id,
          status: ProjectStatus.ACTIVE,
          startDate: new Date(),
          endDate: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000), // 60天后
        },
        {
          name: '营销活动项目',
          description: '策划和执行市场营销活动，提高品牌知名度',
          workspaceId: workspace.id,
          createdById: adminUser.id,
          status: ProjectStatus.ACTIVE,
          startDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天后
          endDate: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000), // 90天后
        }
      ];

      for (const projectData of projectsData) {
        const project = projectRepository.create(projectData);
        await projectRepository.save(project);
        console.log(`为工作区 ${workspace.name} 创建项目: ${project.name}`);
      }
    }

    console.log('项目数据初始化完成');
  }
} 